package com.wanlian.router.ui.manage;

import android.support.annotation.Nullable;
import android.view.View;

import com.smart.android.ui.tools.BaseListFragment;
import com.wanlian.router.bean.Blacklist;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Hyu on 2018/9/2.
 * Email: fvaryu@qq.com
 */
public class BlacklistFragment extends BaseListFragment {

    private List<Blacklist> mBlacklists;
    private BlacklistAdapter mBlacklistAdapter;

    public static BlacklistFragment newInstance() {
        return new BlacklistFragment();
    }


    @Override
    protected void initUI(View view) {
        super.initUI(view);
        mBlacklists = new ArrayList<>();
        setAdapter(mBlacklistAdapter = new BlacklistAdapter(getActivity(), mBlacklists));
    }

    @Override
    protected void initData(View view) {
        super.initData(view);

        mBlacklistAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Blacklist blacklist = (Blacklist) v.getTag();
                NetWorkingClient.getInstance().removeBlack(getActivity(), String.valueOf(blacklist.getId()), new INetCallBack() {
                    @Override
                    public void onFinish(ResponseData response, @Nullable Object o) {
                        if (response.isSuccess()) {
                            showToast("移除成功");
                            autoRefresh();
                        }else {
                            showToast(response.getMessage());
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void loadData(final boolean isRefresh) {
        super.loadData(isRefresh);
        if (!canToLoad(isRefresh)) {
            return;
        }

        NetWorkingClient.getInstance().queryBlackList(getActivity(), getPageInfo(), new INetCallBack<List<Blacklist>>() {
            @Override
            public void onFinish(ResponseData response, @Nullable List<Blacklist> blacklists) {
                resetPull();
                if (response.isSuccess()) {
                    if (isRefresh) {
                        mBlacklists.clear();
                    }

                    if (blacklists != null) {
                        mBlacklists.addAll(blacklists);
                    }

                    mBlacklistAdapter.notifyDataSetChanged();
                }
            }
        });
    }
}
